<?php

class AppModel extends Model {

    function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
        $uniqueCacheId = buildFunctionUid(func_get_args());

        if (!empty($extra['contain'])) {
            $contain = $extra['contain'];
        }
        
        $name = 'pagination-' . $this->alias . '-' . $uniqueCacheId;

        $pagination = Cache::read($name, 'paginate_cache');
        if (empty($pagination)) {
            $pagination = $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group', 'contain'));
            Cache::write($name, $pagination, 'paginate_cache');
            $this->_addToCaches($name);
        }
        return $pagination;
    }
    
    function notifyModelDataChanged() {
        $this->_mcchanged();
    }

    function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
        $uniqueCacheId = buildFunctionUid(func_get_args());

        if (!empty($extra['contain'])) {
            $contain = $extra['contain'];
        }

        $paginationcount = Cache::read('paginationcount-' . $this->alias . '-' . $uniqueCacheId, 'paginate_cache');
        if (empty($paginationcount)) {
            $paginationcount = $this->find('count', compact('conditions', 'contain', 'recursive'));
            Cache::write('paginationcount-' . $this->alias . '-' . $uniqueCacheId, $paginationcount, 'paginate_cache');
            $this->_addToCaches('paginationcount-' . $this->alias . '-' . $uniqueCacheId);
        }
        return $paginationcount;
    }

    public function afterSave($created) {
        parent::afterSave($created);
        $this->_mcchanged();
    }

    public function afterDelete() {
        parent::afterDelete();
        $this->_mcchanged();
    }
    
    private function _mcchanged() {
        $key = "modelcaches-".$this->alias;
        $tdata = Cache::read($key, 'paginate_cache');
        if(!empty($tdata)) {
            $caches = unserialize($tdata);
            foreach($caches as $cache) {
                Cache::delete($cache, 'paginate_cache');
            }
            Cache::delete($key);
        }
    }
    
    private function _addToCaches($name) {
        $key = "modelcaches-".$this->alias;
        $tdata = Cache::read($key, 'paginate_cache');
        if(!empty($tdata)) {
            $caches = unserialize($tdata);
            if(!in_array($name, $caches)) {
                $caches[] = $name;
                Cache::write($key, serialize($caches), 'paginate_cache');
            }
        }
        else {
            Cache::write($key, serialize(array($name)), 'paginate_cache');
        }
    }
}

?>
